//
//  RegisteredAccountVC.m
//  DataStatistics
//
//  Created by Kang on 16/1/4.
//  Copyright © 2016年 YTYangK. All rights reserved.
//
//    dispatch_group_t gruop = dispatch_group_create();
//    // 创建队列 （参数一: 优先级 ，参数二： 未来参数）
//    dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
//    dispatch_group_async(gruop, queue, ^{

//    });
//    dispatch_group_notify(gruop, dispatch_get_main_queue(), ^{
//    });

#import "RegisteredAccountVC.h"
#import "UIButton+countDown.h"
#import "Webview.h"
#import "YJLocalCountryData.h"
#import "isPhoneNumber.h"
//#import <AddressBook/AddressBook.h> //通讯录
#import <SMS_SDK/Extend/SMSSDKCountryAndAreaCode.h>
#import <SMS_SDK/SMSSDK.h>
#import "SectionsViewController.h"
#import "UIView+RGSize.h"
#import <MOBFoundation/MOBFoundation.h>
#import <SMS_SDK/Extend/SMSSDK+ExtexdMethods.h>
#import "UITextField+LolitaText.h"
#import "LoginViewModel.h"
#import "GUAAlertView.h"

#define LABEL ((MLLinkLabel*)self.Continue)
@interface RegisteredAccountVC () <UITextFieldDelegate, UIAlertViewDelegate,UIGestureRecognizerDelegate,SectionsViewControllerDelegate> {
    // 默认View 的Frame
    CGRect frameDefault;
    // 记录是否点击
    BOOL isClick;
    //
    int second;
    //
    UIAlertController* alert;
    
    //  获取到请求的值
    int regisInt;
    
}
@property (strong, nonatomic) IBOutlet UIView* nextView;
//@property (strong, nonatomic) UIButton *eliminateContent;
@property (strong, nonatomic) UIToolbar* topview;  // 容器
@property (strong, nonatomic) UIButton *baritem;   // 键盘上按钮
@property (strong, nonatomic) UIBarButtonItem *item;
@property (retain, nonatomic) NSTimer* timer;
@property (assign, nonatomic, setter=isSuccessful:) BOOL whetherSuccess;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_phoneNum;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_netxtView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_nextview_H;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_viceGuide_top;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* _H_next_Y;


@end

@implementation RegisteredAccountVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self updateUI];
    [self SMSLocalArea];
    [self.SMSCodeBtn setTitle:NSLocalizedString(@"next", @"下一步") forState:UIControlStateNormal];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{   [super viewDidDisappear:animated]; }
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 初始化UI
- (void)updateUI
{
    // 细节调整
    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        _V_nextview_H.constant = 35;
        //__H_next_Y.constant -= 5;
        self.Continue.font = [UIFont systemFontOfSize:12.f];
        self.viceGuideLabel.font = [UIFont systemFontOfSize:13.f];
        if (SCREEN_HEIGHT == 480) {
            _V_phoneNum.constant += 9;
        }
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")){
        self.Continue.font = [UIFont systemFontOfSize:13.f];
        self.viceGuideLabel.font = [UIFont systemFontOfSize:14.f];
        _V_nextview_H.constant = 40;
        self.guideLabel.font = [UIFont boldSystemFontOfSize:19];

    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"736.0")){
        self.guideLabel.font = [UIFont boldSystemFontOfSize:23];
        self.viceGuideLabel.font = [UIFont systemFontOfSize:14.f];

        self.Continue.font = [UIFont systemFontOfSize:14.f];

    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
        
        self.V_netxtView.constant = -35;
        
    }

    isClick = NO;
    frameDefault = self.view.frame;
    
  //新加颜色改变
    self.view.backgroundColor = RGB(33, 38, 44, 1);
    self.nextView.backgroundColor = RGB(26, 32, 40, 1);
     [self iphoneNum];
    
     self.SMSCodeBtn.userInteractionEnabled = NO;
    [self.SMSCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
   //忘记密码
    if ([self.RAVCsignStr isEqualToString:@"Forget"]) {
        self.viceGuideLabel.hidden = YES;
        self.Continue.hidden = YES;
        [self updateForgetUI];
    }
    else if ([self.RAVCsignStr isEqualToString:@"Registered"]) {
        self.viceGuideLabel.height = NO;
        self.Continue.hidden = NO;
        [self updateRegisteredUI];
    }
}

// 更新 注册UI
- (void)updateRegisteredUI
{
    self.title = NSLocalizedString(@"signUp", @"注册");
    self.guideLabel.text = NSLocalizedString(@"RvcLead_0", nil);
    self.viceGuideLabel.text = NSLocalizedString(@"RvcLead_1", nil);

    if (!self.Continue.hidden) {
        // 段落样式
        NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc] init];
        //指定段落
        paragraph.firstLineHeadIndent = 2;
        //调整文字缩进像素
        paragraph.headIndent = 13;

        // 下划线 + 字体
        NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"RvcLead_2", nil)];
        
            [attrStr addAttribute:NSLinkAttributeName value:@"http://www.oilklenze.com.cn/mdc/privacy_policy.html" range:NSMakeRange(14, 4)];
        
            [attrStr addAttribute:NSLinkAttributeName value:@"http://www.oilklenze.com.cn/mdc/terms_of_use.html" range:NSMakeRange((attrStr.length - 5),4)];
        
        self.Continue.attributedText = attrStr;
        self.Continue.textAlignment = NSTextAlignmentLeft;
        self.Continue.textInsets = UIEdgeInsetsMake(1, 18, 5, 5);
        self.Continue.lineHeightMultiple = 1.2f;
        self.Continue.beforeAddLinkBlock = nil;
        self.Continue.dataDetectorTypes = MLDataDetectorTypeAll;
        self.Continue.allowLineBreakInsideLinks = YES;
        self.Continue.linkTextAttributes = nil;
        self.Continue.activeLinkTextAttributes = nil;
        __weak typeof(self) weakSelf = self;
        [self.Continue setDidClickLinkBlock:^(MLLink* link, NSString* linkText, MLLinkLabel* label) {
            NSString* tips = [NSString stringWithFormat:@"Click\nlinkType:%ld\nlinkText:%@\nlinkValue:%@", (unsigned long)link.linkType, linkText, link.linkValue];
            NSLog(@"----->%@", tips);
                [weakSelf gotoWebView:linkText];
        }];

        // 小点
        UIView* vv = [[UIView alloc] initWithFrame:CGRectMake(8, 8, 6, 6)];
        vv.backgroundColor = RGB(14, 118, 199, 1);
        vv.layer.cornerRadius = 4.0f;
        [self.Continue addSubview:vv];
    }
}

// 更新 忘记密码UI
- (void)updateForgetUI
{
    self.title = NSLocalizedString(@"forgotPassword", nil);
    self.guideLabel.text = NSLocalizedString(@"RvcLead_3", nil);
    self.guideLabel.font = [UIFont systemFontOfSize:17.f];
    self.V_viceGuide_top.constant = 16;
}



// 设置地区缓存
- (void)SMSLocalArea {
    // 设置本地区号
    [self setTheLocalAreaCode];
    // 保存记录
    NSString* saveTimeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"saveDate"];
    NSDateComponents* dateComponents = nil;
    if (saveTimeString.length != 0) {
        dateComponents = [YJLocalCountryData compareTwoDays:saveTimeString];
    }
    //day = 0 ,代表今天，day = 1  代表昨天  day >= 1 表示至少过了一天  saveTimeString.length == 0表示从未进行过缓存
    if (dateComponents.day >= 1 || saveTimeString.length == 0) {
        __weak RegisteredAccountVC* regViewController = self;
        
        [SMSSDK getCountryZone:^(NSError* error, NSArray* zonesArray) {
            if (!error) {
                NSLog(@"----->get the area code sucessfully");
                //区号数据
                
                regViewController.areaArray = [NSMutableArray arrayWithArray:zonesArray];
                [[MOBFDataService sharedInstance] setCacheData:regViewController.areaArray forKey:@"countryCodeArray" domain:nil];
                
                //设置缓存时间
                NSDate* saveDate = [NSDate date];
                [[NSUserDefaults standardUserDefaults] setObject:[MOBFDate stringByDate:saveDate withFormat:@"yyyy-MM-dd"] forKey:@"saveDate"];
                
                NSLog(@"_areaArray_%@", regViewController.areaArray);
            }
            else {
                NSLog(@"failed to get the area code _%@______error_%@", [error.userInfo objectForKey:@"getZone"], error);
            }
        }];
    }
    else {
        _areaArray = [[MOBFDataService sharedInstance] cacheDataForKey:@"countryCodeArray" domain:nil];
    }

}

// 设置本地区号
- (void)setTheLocalAreaCode
{
    _areaCode.text = @"+86";
    _areaName.text = @"中国";
}

/** 跳转协议 */
- (void)gotoWebView:(NSString*)keyStr
{
    // 下一页返回的字样
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title = NSLocalizedString(@"back", nil);
    self.navigationItem.backBarButtonItem = backIetm;
    
    Webview* web = [[Webview alloc] init];
    web.title = keyStr;
    web.hidesBottomBarWhenPushed = YES;
    web.identificationStr = keyStr;

    [self.navigationController pushViewController:web animated:YES];
}

// 限制长度
- (void)textLengthMethod:(UITextField*)textField
{

    if (textField.text.length > 0) {
        self.SMSCodeBtn.userInteractionEnabled = YES;
        [self.SMSCodeBtn setTitleColor:RGB(253, 135, 59, 1) forState:UIControlStateNormal];
        _baritem.userInteractionEnabled = YES;
        [_baritem setTitleColor:RGB(253, 135, 59, 1) forState:UIControlStateNormal];
    }
    else {
        self.SMSCodeBtn.userInteractionEnabled = NO;
        [self.SMSCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        _baritem.userInteractionEnabled = NO;
        [_baritem setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }

    if (textField == _iphoneNum) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}

/// 监控键盘 - 显示
- (void)LTkeyboardWillShow:(NSNotification*) not
{
    if (!isClick) {
        isClick = YES;
        [_iphoneNum becomeFirstResponder];
    }
    
    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        _topview.alpha = 0.0;
        CGRect newFrome = self.view.frame;
        if (SCREEN_HEIGHT == 480) {
            newFrome.origin.y = -1 * 36;
        }
        else {
            newFrome.origin.y = 40;
        }
        
        [UIView animateWithDuration:0.24 animations:^{
            _topview.alpha = 1.0;
            [self.view setFrame:newFrome];
        }
                         completion:^(BOOL finished){
                             
                         }];
    }

    
}
// 监控键盘 - 隐藏
- (void)LTkeyboardWillHide:(NSNotification*) not
{
    [self resignRespondersForText];
}


#pragma mark - TextField Delegate
// 禁止输入框长按复制\拷贝功能
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{

    if (action == @selector(paste:))
        return NO;

    if (action == @selector(copy:))
        return NO;

    if (action == @selector(cut:))
        return NO;

    return [super canPerformAction:action withSender:sender];
}

// 隐藏键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (isClick == YES) {
        isClick = NO;
       [_iphoneNum resignFirstResponder];
    }
}



- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIButton class]]) {
        return NO;
    }
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UIButton"]) {
        return NO;
    }
    return YES;
}


//输入框清空后调用的方法
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    NSString *str = _iphoneNum.text;
    if (str.length >0) {
        _iphoneNum.enablesReturnKeyAutomatically  = YES;
         _baritem.userInteractionEnabled = NO;
        [_baritem setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.SMSCodeBtn.userInteractionEnabled = NO;
        [self.SMSCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
    return YES;
}


#pragma mrak - SMS请求、校验注册是否已存在
- (IBAction)clickSMSPinCodeBtn:(id)sender
{
    
    
    NSString *str = _iphoneNum.text;
    if (![isPhoneNumber isMobile:str]) {
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"请输入合法的手机号码" toView:self.view];
    }else{
        [self.view endEditing:YES];

        // ???:校验账号
        NSString* str2 = [self.areaCode.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_iphoneNum.text,@"loginName",str2,@"zone",nil];
        
        [LoginViewModel requestWithUrlForRegisteredAccountSign:self.RAVCsignStr andParam:dic success:^(id model) {
            
            
            
            
                NSString* str = [NSString stringWithFormat:@"%@:%@ %@", NSLocalizedString(@"RvcLead_4", nil), self.areaCode.text, _iphoneNum.text];
                

                GUAAlertView *v = [GUAAlertView alertViewWithTitle:@"请确认手机号码"
                                                           message:str
                                                       buttonTitle:@"发送"
                                               buttonTouchedAction:^{
                                                   NSLog(@"button touched");
                                                   
                                                   if ([model isEqualToString:@"success"]) {
                                                       if ([self.areaCode.text isEqualToString:@"+86"]) {
                                                           if ([isPhoneNumber isMobileNumber:_iphoneNum.text] == NO) {
                                                               // [self resignRespondersForText];
                                                               [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"RvcTip_1", nil) toView:self.view];
                                                           }
                                                           else {
                                                               [self SMSSDK];
                                                           }
                                                       }
                                                       else {
                                                           [self SMSSDK];
                                                       }
                                                   }else {
                                                       if ([model isEqualToString:@"error"]) {
                                                           if ([_RAVCsignStr isEqualToString:@"Forget"]) {
                                                               [self SMSSDK];
                                                           }
                                                       }
                                                   }
                                                    [_iphoneNum resignFirstResponder];

                                               } dismissAction:^{
                                                   NSLog(@"dismiss");
                                                   
                                               }];
            
                [v show];
        } failure:^(NSString *err) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:err toView:self.view];
        }];
    }
}


- (void)SMSSDK
{
    /**
     *  发送SMS 短信
     */
        NSString* str2 = [self.areaCode.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_iphoneNum.text zone:str2 customIdentifier:nil result:^(NSError *error) {

            if (!error) {
                // 成功获取
                if ([self.RAVCsignStr isEqualToString:@"Forget"]) {
                    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
                    backIetm.title = NSLocalizedString(@"back", nil);
                    self.navigationItem.backBarButtonItem = backIetm;
                }

                [self performSegueWithIdentifier:@"RegisteredVerification" sender:self];
                 [_iphoneNum resignFirstResponder];

            }else {
               NSString *messageStr = [NSString stringWithFormat:@"%zidescription",error.code];
                [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(messageStr, nil) toView:self.view];
            }
      }];
}

// 电话验证
- (BOOL)checkPhoneNumber:(NSString*)phoneNumber
{
    NSError* error = NULL;
    NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];

    NSRange inputRange = NSMakeRange(0, [phoneNumber length]);
    NSArray* matches = [detector matchesInString:phoneNumber options:0 range:inputRange];

    BOOL verified = NO;

    if ([matches count] != 0) {
        // found match but we need to check if it matched the whole string
        NSTextCheckingResult* result = (NSTextCheckingResult*)[matches objectAtIndex:0];

        if ([result resultType] == NSTextCheckingTypePhoneNumber && result.range.location == inputRange.location && result.range.length == inputRange.length) {
            // it matched the whole string
            verified = YES;
        }
        else {
            // it only matched partial string
            verified = NO;
            ;
        }
    }
    return verified;
}


#pragma mark - resign responders
- (void)resignRespondersForText
{
    // 隐藏键盘时动画
       _topview.alpha = 1.0;
//    self.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
            [UIView animateWithDuration:0.5 animations:^{
                _topview.alpha = 0.0;
                [self.view setFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
               }completion:^(BOOL finished){}];
        }
}

// 选择国家区号
- (IBAction)clickArea:(UIButton*)sender
{
    [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"暂不支持国外手机号注册" toView:nil];
}
#pragma mark - SecondViewControllerDelegate的方法
- (void)setSecondData:(SMSSDKCountryAndAreaCode*)data
{
    NSLog(@"the area data：%@,%@", data.areaCode, data.countryName);
    self.areaName.text = [NSString stringWithFormat:@"%@", data.countryName];
    self.areaCode.text = [NSString stringWithFormat:@"+%@", data.areaCode];
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
    NSString* str2 = [self.areaCode.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
    if ([segue.identifier compare:@"RegisteredVerification"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:_RAVCsignStr forKey:@"VVCsignStr"];
        [vc setValue:_iphoneNum.text forKey:@"VVC_phoneNumber"];
        [vc setValue:str2 forKey:@"VVC_areaNam"];
        [vc setValue:_window forKey:@"VVC_window"];
    }
}

#pragma  mark - get/set
// 键盘－ 按钮
- (UIToolbar *)topview {
    if (!_topview) {
        _topview = [UITextField topView];
        [_topview addSubview:self.baritem];
    }
    return _topview;
}

- (UIButton *)baritem {
    if (!_baritem) {
        _baritem =[UITextField barItem];
        [_baritem addTarget:self action:@selector(clickSMSPinCodeBtn:) forControlEvents:UIControlEventTouchDown];
        
        self.item = [[UIBarButtonItem alloc] initWithCustomView:self.baritem];
        UIBarButtonItem *flexibleitem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:self action:nil];
        NSArray *items = @[flexibleitem,flexibleitem,_item];
        [self.topview setItems:items animated:YES];
    }
    return _baritem;
}

- (UITextField *)iphoneNum {
    if (!_iphoneNum) {}

    _iphoneNum.delegate = self;
    [_iphoneNum addObserverForWillKeyBoard:self]; //添加了监听
    [UITextField addYTYanKTextFielStyle1:_iphoneNum withString:NSLocalizedString(@"RvcLead_6", nil)];
    [_iphoneNum addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    [_iphoneNum setInputAccessoryView:self.topview];
    return _iphoneNum;
}

@end
